<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.id" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="请输入品牌商ID"
      />
      <el-input v-model="listQuery.name" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="请输入品牌商名称"
      />
      <el-button v-permission="['GET /admin/brand/list']" size="mini" class="filter-item" type="primary"
                 icon="el-icon-search" @click="handleFilter"
      >查找
      </el-button>
      <el-button v-permission="['POST /admin/brand/create']" size="mini" class="filter-item" type="primary"
                 icon="el-icon-edit" @click="handleCreate"
      >添加
      </el-button>
      <el-button :loading="downloadLoading" size="mini" class="filter-item" type="warning" icon="el-icon-download"
                 @click="handleDownload"
      >导出
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit
              highlight-current-row
    >

      <el-table-column align="center" min-width="100px" label="品牌商ID" prop="id" sortable/>

      <el-table-column align="center" min-width="150px" label="品牌商名称" prop="name"/>

      <el-table-column align="center" min-width="100px" property="picUrl" label="品牌商图片">
        <template slot-scope="scope">
          <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="80">
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="350px" label="介绍" prop="desc"/>

      <!--      <el-table-column align="center" min-width="80px" label="底价" prop="floorPrice"/>-->

      <el-table-column align="center" label="操作" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--          <el-button type="primary" size="mini" @click="shareUrlDetail(scope.row)">推广码</el-button>-->
          <el-button v-permission="['POST /admin/brand/update']" type="primary" size="mini"
                     @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button v-permission="['POST /admin/brand/delete']" type="danger" size="mini"
                     @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <!-- 店铺二维展示框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="shareUrlDialogVisible" width="700">
      <el-form :data="dataForm" label-position="left">
        <el-form-item label="推广二维码">
          <img :src="dataForm.shareUrl" width="300">
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="120px"
               style="margin-left:50px;"
      >
        <el-form-item label="品牌商名称" prop="name">
          <el-input v-model="dataForm.name"/>
        </el-form-item>
        <!--        <el-form-item label="主营类目">-->
        <!--          <el-cascader :options="categoryList" v-model="dataForm.categoryIds" expand-trigger="hover" @change="handleCategoryChange"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="管理员">
          <el-select v-model="dataForm.adminId">
            <el-option v-for="item in adminList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="介绍" prop="desc">
          <el-input v-model="dataForm.desc"/>
        </el-form-item>
        <el-form-item label="门店图片" prop="picUrl">
          <shop-up-load :pic-url.sync="dataForm.picUrl"
                        :crop-width="800"
                        :crop-height="506"
          />
          <!--          <el-upload-->
          <!--            :headers="headers"-->
          <!--            :action="uploadPath"-->
          <!--            :show-file-list="false"-->
          <!--            :on-success="uploadPicUrl"-->
          <!--            class="avatar-uploader"-->
          <!--            accept=".jpg,.jpeg,.png,.gif">-->
          <!--            <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar">-->
          <!--            <i v-else class="el-icon-plus avatar-uploader-icon"/>-->
          <!--          </el-upload>-->
        </el-form-item>
        <!--        <el-form-item label="底价" prop="floorPrice">-->
        <!--          <el-input v-model="dataForm.floorPrice"/>-->
        <!--        </el-form-item>-->

        <el-form-item label="提货时间设置" prop="fetchTimeRules">
          <el-tag v-for="tag in dataForm.fetchTimeRules" :key="tag" closable type="primary" @close="handleClose(tag)">
            {{ tag }}
          </el-tag>
          <el-time-picker
            v-if="newTimeRulesVisible"
            ref="newTimeRulesInput"
            v-model="newTimeRules"
            format="HH:mm"
            value-format="HH:mm"
            class="input-new-time-rules"
            size="small"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-time-rules" size="small" type="primary" @click="addTimeRules">+ 增加
          </el-button>
        </el-form-item>

        <el-form-item label="自提地址" prop="address">
          <el-input v-model="dataForm.address"/>
        </el-form-item>

        <el-form-item label="经度值" prop="longitude">
          <el-input v-model="dataForm.longitude" style="width: 120px;" placeholder="输入经度值"/>
        </el-form-item>
        <el-form-item label="纬度值" prop="latitude">
          <el-input v-model="dataForm.latitude" style="width: 120px;" placeholder="输入纬度值"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="goLbs">获取经纬度</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-time-rules {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

</style>

<script>
import { createBrand, deleteBrand, listBrand, listCatAndAdmin, updateBrand } from '@/api/business/brand'
import { uploadPath } from '@/api/business/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import ShopUpLoad from '@/components/ShopUpLoad' // Secondary package based on el-pagination

export default {
  name: 'Brand',
  components: { ShopUpLoad, Pagination },
  data() {
    return {
      uploadPath,
      list: undefined,
      total: 0,
      categoryList: [],
      adminList: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        name: '',
        desc: undefined,
        floorPrice: undefined,
        picUrl: undefined,
        categoryIds: [],
        defaultCategoryId: undefined,
        adminId: undefined,
        address: undefined,
        longitude: undefined,
        latitude: undefined,
        fetchTimeRules: []
      },
      dialogFormVisible: false,
      shareUrlDialogVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建',
        shareUrl: '店铺推广码'
      },
      rules: {
        name: [
          { required: true, message: '品牌商名称不能为空', trigger: 'blur' }
        ],
        picUrl: [
          { required: true, message: '门店图片不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '介绍不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '自提地址不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '纬度值不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '经度值不能为空', trigger: 'blur' }
        ],
        fetchTimeRules: [
          { required: false, message: '自提时间不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      newTimeRules: '',
      fetchTimeRules: [],
      newTimeRulesVisible: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Dts-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
    this.init()
  },
  methods: {
    init: function() {
      listCatAndAdmin().then(response => {
        this.categoryList = response.data.data.categoryList
        this.adminList = response.data.data.adminList
      })
    },
    getList() {
      this.listLoading = true
      listBrand(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: '',
        desc: '',
        floorPrice: undefined,
        picUrl: undefined,
        categoryIds: [],
        defaultCategoryId: undefined,
        adminId: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadPicUrl: function(response) {
      this.dataForm.picUrl = response.data.url
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createBrand(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.fetchTimeRules = this.dataForm.fetchTimeRules ? this.dataForm.fetchTimeRules : []
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateBrand(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteBrand(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleCategoryChange(value) {
      this.dataForm.defaultCategoryId = value[value.length - 1]
    },
    shareUrlDetail(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'shareUrl'
      this.shareUrlDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '品牌商ID',
          '品牌商名称',
          '介绍',
          '低价',
          '品牌商图片'
        ]
        const filterVal = ['id', 'name', 'desc', 'floorPrice', 'picUrl']
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          '品牌商信息'
        )
        this.downloadLoading = false
      })
    },
    addTimeRules() {
      this.newTimeRulesVisible = true
    },
    goLbs() {
      const href = 'https://lbs.qq.com/tool/getpoint/index.html'
      window.open(href, '_blank', 'toolbar=yes, width=1300, height=900')
    },
    handleClose(tag) {
      this.fetchTimeRules.splice(this.fetchTimeRules.indexOf(tag), 1)
      this.dataForm.fetchTimeRules = this.fetchTimeRules
    },
    handleInputConfirm() {
      const newTimeRules = this.newTimeRules
      if (newTimeRules && newTimeRules.length > 1) {
        this.fetchTimeRules.push(newTimeRules[0] + ' - ' + newTimeRules[1])
        this.dataForm.fetchTimeRules = this.fetchTimeRules
      }
      this.newTimeRulesVisible = false
      this.newTimeRules = ''
    }
  }
}
</script>
<style type="text/css">
.el-upload{
  width: auto !important;
}
</style>
